<?php
/**
 * Created by PhpStorm.
 * User: xuyiping
 * Date: 2018/7/5
 * Time: 11:26
 */
namespace app\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Libraries\Small\WXBizDataCrypt;
use App\Libraries\Small\WxSmallService;
use App\Model\GoldBeanModel;
use App\Model\WebUserModel;
use Illuminate\Http\Request;

class LoginController extends Controller{

    const APPID = 'wxe66483d456d1bc4e';
    const SECRET = '3a61d37e5c3f2c361fa2663d0b9f4047';

    //登录接口
    public function index(Request $request){

        $code = $request->input('code');

        if(!isset($code) || empty($code)){
            return response()->json(array('code' => 400,'message' => 'code值不能为空'));
        }

        $url = 'https://api.weixin.qq.com/sns/jscode2session?appid='.self::APPID.'&secret='.self::SECRET.'&js_code='.$code.'&grant_type=authorization_code';

        $res_data = WxSmallService::get($url);

        if($res_data['code'] == 200){
            $res_data = $res_data['data'];
            if(!isset($res_data['openid']) || !isset($res_data['session_key'])){
                return response()->json(array('code' => 400,'message' => 'code值无效'));
            }else{

                $user_data = WebUserModel::where('iOpendId',$res_data['openid'])->first();
                if($user_data){
                    WebUserModel::where('iOpendId',$res_data['openid'])->update([
                        'iRegistTime'  => date('Y-m-d H:i:s'),
                        'sLastTime'    => time(),
                        'iSession_key' => $res_data['session_key']
                    ]);
                    $uuid = $user_data->iUUID;
                }else{
                    $uuid = makeUuid();
                    //创建用户信息
                    $user_id = WebUserModel::insertGetId([
                        'iUUID'        => $uuid,
                        'iOpendId'     => $res_data['openid'],
                        'sUnionid'     => isset($res_data['unionid']) ? $res_data['unionid'] : '',
                        'iSession_key' => $res_data['session_key'],
                        'iRegistTime'  => date('Y-m-d H:i:s'),
                        'sLastTime'    => time()
                    ]);

                    //创建用户金豆信息
                    GoldBeanModel::insertGetId([
                        'iUserId'      => $user_id,
                        'iAllGoldBean' => 300,
                        'iNowGoldBean' => 300,
                        'dtCommitTime' => date('Y-m-d H:i:s'),
                        'dtModifyTime' => date('Y-m-d H:i:s'),
                        'sModifyUser'  => 'system'
                    ]);
                }
                return response()->json(array('code' => 200,'message' => '操作成功','data'=>['uuid'=>$uuid]));
            }
        }else{
            return response()->json(array('code' => 400,'message' => '网络错误！'));
        }

    }

    //同步用户资料详情
    public function details(Request $request){
        return false;
        $nickName = $request->input('nickName');
        $avatarUrl = $request->input('avatarUrl');
        $gender = $request->input('gender');
        $city = $request->input('city');
        $province = $request->input('province');
        $country = $request->input('country');
        $uuid = $request->input('uuid');

        if(!isset($uuid) || empty($uuid)){
            return response()->json(array('code' => 400,'message' => '用户UUID不能为空！','data'=>[]));
        }

        $user_data = WebUserModel::where('iUUID',$uuid)->first();
        if(!$user_data){
            return response()->json(array('code' => 400,'message' => '用户不存在，请重新登录！','data'=>[]));
        }

        if(!isset($nickName) || empty($nickName)){
            return response()->json(array('code' => 400,'message' => '微信昵称不能为空！','data'=>[]));
        }
        if(!isset($avatarUrl) || empty($avatarUrl)){
            return response()->json(array('code' => 400,'message' => '微信图像不能为空！','data'=>[]));
        }
        if(!isset($city) || empty($city)){
            return response()->json(array('code' => 400,'message' => '用户城市名不能为空！','data'=>[]));
        }
        if(!isset($province) || empty($province)){
            return response()->json(array('code' => 400,'message' => '用户所在省份不能为空！','data'=>[]));
        }
        if(!isset($country) || empty($country)){
            return response()->json(array('code' => 400,'message' => '用户所在国家不能为空！','data'=>[]));
        }

        if(WebUserModel::where('iUUID',$uuid)->update([
            'sUserImage'  => $avatarUrl,
            'sUserName'  => $nickName,
            'sGender'    => isset($gender)?$gender:0,
            'sCity'  => $city,
            'sProvince'  => $province,
            'sCountry'  => $country,
        ])){
            return response()->json(array('code' => 200,'message' => '操作成功！','data'=>['uuid'=>$uuid]));
        }else{
            return response()->json(array('code' => 400,'message' => '操作失败！','data'=>[]));
        }
    }

    public function user_details(Request $request){

        $encryptedData = $request->input('encryptedData');
        $iv            = urldecode($request->input('iv'));
        $uuid          = $request->input('uuid');

        if(!isset($encryptedData) || empty($encryptedData)){
            return response()->json(array('code' => 400,'message' => 'encryptedData不能为空！','data'=>[]));
        }
        if(!isset($uuid) || empty($uuid)){
            return response()->json(array('code' => 400,'message' => '用户uuid不能为空！','data'=>[]));
        }

        if(strlen($iv) != 24){
            return response()->json(array('code' => 400,'message' => '非法参数iv！','data'=>[]));
        }

        $web_user = WebUserModel::where('iUUID',$uuid)->first();

        if(!$web_user){
            return response()->json(array('code' => 400,'message' => '当前用户不存在！','data'=>[]));
        }

        $pc = new WXBizDataCrypt(self::APPID,$web_user->iSession_key);
        $errCode = $pc->decryptData($encryptedData, $iv, $data );

        if ($errCode == 0) {
            $user_array = json_decode($data,true);
            $user_dateils = [
                'sUserImage' => $user_array['avatarUrl'],
                'sCountry'   => $user_array['country'],
                'sUserName'  => urlencode($user_array['nickName']),
                'sGender'    => $user_array['gender'],
                'sProvince'  => $user_array['province'],
                'iOpendId'   => $user_array['openId'],
            ];
            WebUserModel::where('iUUID',$uuid)->update($user_dateils);
            return response()->json(array(
                'code' => 200,
                'message' => '获取用户信息成功！',
                'data'=>[
                    'uuid'=>$uuid,
                    'user_details'=> [
                        'sUserImage' => $user_array['avatarUrl'],
                        'sCountry'   => $user_array['country'],
                        'sUserName'  => urlencode($user_array['nickName']),
                        'sGender'    => $user_array['gender'],
                        'sProvince'  => $user_array['province'],
                        'iOpendId'   => $user_array['openId'],
                    ]]));

        } else {

            return response()->json(array('code' => 400,'message' => '获取用户信息失败！','data'=>[]));
        }
    }

    //同步用户手机号
    public function phone(Request $request){

        $uuid = $request->input('uuid');
        $phone = $request->input('phone');
        if(!isset($uuid) || empty($uuid)){
            return response()->json(array('code' => 400,'message' => '用户UUID不能为空！','data'=>[]));
        }
        if(!isset($phone) || empty($phone)){
            return response()->json(array('code' => 400,'message' => '用户手机号不能为空！','data'=>[]));
        }

        $user_data = WebUserModel::where('iUUID',$uuid)->first();
        if(!$user_data){
            return response()->json(array('code' => 400,'message' => '用户不存在，请重新登录！','data'=>[]));
        }

        if(WebUserModel::where('iUUID',$uuid)->update([
            'sUserPhone'  => $phone
        ])){
            return response()->json(array('code' => 200,'message' => '操作成功！','data'=>['uuid'=>$uuid]));
        }else{
            return response()->json(array('code' => 400,'message' => '操作失败！','data'=>[]));
        }
    }

}